package com.kc.web.controller.business;

import com.kc.business.domain.order.dto.BizOrderGoodsDTO;
import com.kc.business.domain.vo.KcOrderGoodsVo;
import com.kc.business.service.KcOrderGoodsService;
import com.kc.common.constant.HttpStatus;
import com.kc.common.core.controller.BaseController;
import com.kc.common.core.domain.AjaxResult;
import com.kc.common.core.page.TableDataInfo;
import com.kc.common.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * FileName:   BizOrderGoodsController
 * Author:     TP
 * Date:       12/29/20 8:57 AM
 * Description:
 */
@Slf4j
@RestController
@RequestMapping("/orderGoods")
public class BizOrderGoodsController extends BaseController {

    @Autowired
    private KcOrderGoodsService orderGoodsService;


    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('business:orderGoods:list')")
    public TableDataInfo getList(@Validated KcOrderGoodsVo vo) {
        long days = vo.getSaleDateEnd().toEpochDay() - vo.getSaleDateStart().toEpochDay();
        if (days > 180) {
            TableDataInfo error = new TableDataInfo();
            error.setCode(HttpStatus.ERROR);
            error.setMsg("不能查询超过180天的数据");
            return error;
        }
        startPage();
        List<BizOrderGoodsDTO> list = orderGoodsService.getList(vo);
        return getDataTable(list);
    }

    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermi('business:orderGoods:export')")
    public AjaxResult export(@Validated KcOrderGoodsVo vo, HttpServletResponse response) throws Exception {
        long days = vo.getSaleDateEnd().toEpochDay() - vo.getSaleDateStart().toEpochDay();
        if (days > 180) {
            return AjaxResult.error(600, "不能下载超过180天的数据");
        }
        int no = 1;
        List<BizOrderGoodsDTO> list = orderGoodsService.getList(vo);
        if (CollectionUtils.isNotEmpty(list)) {
            for (BizOrderGoodsDTO dto : list) {
                dto.setNo(no++);
            }
        }
        ExcelUtil<BizOrderGoodsDTO> util = new ExcelUtil<>(BizOrderGoodsDTO.class);
        Workbook workbook = null;
        try {
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            workbook = util.exportExcelWithoutPersist(list, "销售报表");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", String.format("attachment;filename=%s.xlsx",
                    URLEncoder.encode(String.format("销售报表(%s至%s)",
                            vo.getSaleDateStart().format(dtf),
                            vo.getSaleDateEnd().format(dtf)),
                            "UTF-8")));
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        } finally {
            if (null != workbook) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}